R for College Mathematics and Statistics by Pfaff Thomas;

R for College Mathematics and Statistics by Pfaff Thomas;

Author:Pfaff, Thomas;
Language: eng
Format: epub
Publisher: CRC Press LLC


9.3 Log Fit

We use rnorm to generate random data for our example of fitting a log function to data. We have not set a seed so results will differ. We let x be the integers from 3 to 100 using the colon command. We then define y to be log(x) (in R log is the natural log function) plus some “noise” added with rnorm. Here our call to rnorm returns a vector of length(x) values from a random normal distribution with mean zero and standard deviation 0.25. Note that y is a vector with the same length as x since the addition of the two vectors,log(x) and rnorm, is element-wise. A simple plot is created with plot (x,y). The Im functions returns the results from fitting the data with the model y = log(x) + b, which is set to the variable Log.fit. The function Log.fit.function is defined using the coefficients returned from coef(Log.fit) and added to the graph with curve. The functions summary(Log.fit), names(Log.fit), and coef(Log.fit) will return information similar to that demonstrated in the Exponential Fit Section.

R Code

> x=3:100

> y=log(x) + rnorm(length(x),0,0.25)

> plot(x,y)

> Log.fit=lm(y~log(x))

> Log.fit.function=function(x)

{coef(Log.fit)[2]*log(x)+coef(Log.fit)[1]}

> curve(Log.fit.function,0,100,lwd=2,add=TRUE)



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.